<template>
  <div>
    <a href="javascript:;" class="file">
      {{name}}
      <input type="file" ref="upload" @change="uploadImg" name id />
    </a>
  </div>
</template>
<script>
import config from "../utils/config";

export default {
  name: "upload",
  props: {
    name: {
      type: String,
      default() {
        return "新增";
      }
    },
    type: {
      type: String,
      default() {
        return "carousel";
      }
    }
  },
  data() {
    return {};
  },
  methods: {
    //上传图片
    uploadImg(e) {
      var that = this;
      let files = e.target.files;
      if (files.length > 1) {
        this.$message.error("只能上传单张图片");
        this.$refs.upload.value = "";
      } else {
        let file = files[0];
        let type = file.type; //文件的类型，判断是否是图片
        let size = file.size; //文件的大小，判断图片的大小
        let imgData = { accept: "image/gif, image/jpeg, image/png, image/jpg" };
        if (imgData.accept.indexOf(type) == -1) {
          this.$message.error("只支持图片格式上传");
          return false;
        }
        if (size > 25 * 1024 * 1024) {
          this.$message.error("图片大小不允许超过25M,请重试");
          this.$refs.upload.value = "";
          return false;
        }
        const loading = this.$loading({
          lock: true,
          text: "上传中",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)"
        });

        let formData = new FormData();
        formData.append("image", file); //‘file’是後台接收文件名
        formData.append("type", this.type); //‘file’是後台接收文件名
        that
          .$upload("upload/picture", formData)
          .then(datas => {
            if (datas.code == 200) {
              const { data } = datas;
              that.$refs.upload.value = "";
              loading.close();
              this.$emit(
                "saveCb",
                `${config.HOST}/api/file/${data.images.url}`,
                this.uuid()
              );
            } else {
              loading.close();
              that.$message.error("未知错误");
              that.$refs.upload.value = "";
            }
          })
          .catch(() => {
            loading.close();
          });
      }
    },
    uuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        let r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    }
  }
};
</script>
<style lang="less" scoped>
.file {
  position: relative;
  display: inline-block;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 36px;
}
.file input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
</style>